﻿using AutoMapper;
using MediatR;
using SmartCity.BasicData.Api.Application.Commond.ADepartMent;
using SmartCity.BasicData.Common;
using SmartCity.BasicData.Domain;
using SmartCity.BasicData.Repo;
using System.Collections.Generic;

namespace SmartCity.BasicData.Api.Application.Handler.ADepartment
{
    /// <summary>
    /// 
    /// </summary>
    public class GetDepartmentHandler : IRequestHandler<GetDepartmentCommand, ApiResult<IList<ADepartMentDTO>>>
    {
        private readonly IBaseRepository<DepartmentsModel> departRepo;
        private readonly IMapper mapper;

        public GetDepartmentHandler(IBaseRepository<DepartmentsModel> departRepo,IMapper mapper)
        {
            this.departRepo = departRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<IList<ADepartMentDTO>>> Handle(GetDepartmentCommand request, CancellationToken cancellationToken)
        {
            ApiResult<IList<ADepartMentDTO>> result = new ApiResult<IList<ADepartMentDTO>>();

            try
            {
                result.Data = GetDepartmentTree(0);

            }
            catch (Exception e)
            {

                throw e;
            }

            result.Code = Common.Menus.EnumResultCode.Success;
            result.Msg = "获取级联数据成功!";

            return Task.FromResult(result);
        }

        private IList<ADepartMentDTO> GetDepartmentTree(long parentId=0) {
            var departModels = departRepo.GetAsync(d=>d.ParentId== parentId).Result; //政府 公安
            var departDTOs = mapper.Map<IList<ADepartMentDTO>>(departModels);//第一层转换好了
            foreach (var item in departDTOs)
            {
                item.Childrens = GetDepartmentTree(item.Id);
            }
            return departDTOs;
        }
    }
}
